import React from 'react';
import {connect} from "react-redux";
import {Button, Input, Badge, message, Row, Col, Card, Icon, Modal, Popover} from 'antd';
import menuRoute from "routes/menuRoute";
import {deepCopy, messages} from "share/common";
import taxCodeServer from 'containers/finance-setting/tax-code/tax-code-server';
import errorMessage from "share/errorMessage";
import chooserData from 'share/chooserData'
import TaxCodeTreeSelector from 'containers/finance-setting/tax-code/tax-code/invoice-type/tax-code-tree-selector'
import CCService from "../../../../setting/cost-center/cost-center.service";
import ResizeTable from 'components/resize-table'
const Search = Input.Search;

class TaxCodeClassify extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0
      },
      dataAll: false,//是否全选的标志
      reverseSelectionMap: {},//当全选的时候，记住这些没勾选的,每一页一个key
      columns: [
        {
          title: messages('common.sequence')/*序号*/,
          dataIndex: "index",
          width: "5%",
          render: (value, record, index) => this.state.pageSize * this.state.page + index + 1
        },
        {title: messages('finance-setting.key126'/*商品和服务类分类简称*/), dataIndex: "goodsServiceShortName", width: "15%"},
        {title: messages('finance-setting.key127'/*货物和劳务名称*/), dataIndex: "goodsServiceName", width: "15%"},
        {title: messages('finance-setting.key128'/*合并编码*/), dataIndex: "taxCode", width: "15%"},
        {
          title: messages('finance-setting.key129'/*说明*/), dataIndex: "description", width: "40%", render: value => {
            return <Popover content={value}>{value}</Popover>
          }
        },
        {
          title: messages('common.column.status')/*状态*/, dataIndex: "enable", width: "10%", render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages("common.status.enable") : messages("common.status.disable")}/>)
        }],
      showTaxCodeModal: false,//显示新增税务编码Modal
      invoiceTypeInfo: this.props.location.state ? this.props.location.state.invoiceTypeInfo : {},//费用类型编码规则信息
      dataList: [],//规则list信息
      selectedRowKeys: [],//选中的行，用于启用或者禁用
      searchParam: "",//搜索的变量用于全选全部
      taxCodeSelectItem: chooserData['selectInvoiceType'],
      currentSelectedTaxCodeData: []
    }
  }
  componentWillMount() {
    if (!this.state.invoiceTypeInfo.id) {
      let {audRuleExpTypeId} = this.props.params;
      this.queryInvoiceTypeInfo(audRuleExpTypeId);
    }
    this.getList();
  }

  componentDidMount() {

  }

  //查询单个规则信息
  queryInvoiceTypeInfo(audRuleExpTypeId) {
    taxCodeServer.queryTaxCodeRelateInvoiceTypeInfo(audRuleExpTypeId).then(res => {
      this.setState({
        invoiceTypeInfo: res.data
      })
    }).catch(e => {
      errorMessage(e.response)
    })
  }

  //批量启用、禁用
  clickEnable = (enable) => {
    let {selectedRowKeys, reverseSelectionMap, dataList, searchParam, dataAll} = this.state;
    let {audRuleExpTypeId} = this.props.params;
    let params;
    //反选模式
    if (dataAll) {
      params = {
        audRuleExpTypeId: audRuleExpTypeId,
        excludeIds: CCService.getReverseSelection(deepCopy(reverseSelectionMap)),
        enable: enable,
        modelEnum: "ALL_PAGE",
        searchParam
      }
    } else {
      params = {
        audRuleExpTypeId: audRuleExpTypeId,
        currentPageIds: selectedRowKeys,
        enable: enable,
        modelEnum: null,
        searchParam
      }
    }
    this.setState({loading:true})
    taxCodeServer.enableExpenseTypeTaxNumber(params).then(res => {
      this.setState({loading:false})
      dataList.map(item => {
        if (~selectedRowKeys.indexOf(item.id)) {
          item.enable = enable;
        }
      })
      this.setState({selectedRowKeys: [], dataList});

      message.success(messages('common.operate.success')/*操作成功*/);
    }).catch(e => {
      this.setState({loading:false})
      errorMessage(e.response);
    })
  }
  //模糊查询
  searchList = (searchParam) => {
    let {pagination}=this.state;
    pagination.page=0;
    pagination.current=0;
    this.setState({
      dataAll: false,
      selectedRowKeys: [],
      reverseSelectionMap: {},
      page: 0,
      pagination,
      searchParam
    },()=>{
      this.getList();
    })
  }
  //获取规则列表
  getList = () => {
    let {page, pageSize, dataAll, reverseSelectionMap,searchParam} = this.state;
    let {audRuleExpTypeId} = this.props.params;
    this.setState({loading: true})
    taxCodeServer.queryExpenseTypeTaxNumber(audRuleExpTypeId, page, pageSize, searchParam).then(res => {
      let {pagination} = this.state;
      pagination.total = res.data.total;
      let ids = [];
      res.data.rows && res.data.rows.map((item) => {
        item.key = item.id;
        ids.push(item.id);
      });
      this.setState({
        dataList: res.data.rows,
        loading: false,
        searchParam,
        pagination
      }, () => {
        if (dataAll) {
          //如果有全选全部,翻页就立即勾选,并且需要排除掉没有勾选的
          let currentPageUnselected = reverseSelectionMap[this.state.page];
          let currentPageSelected = CCService.getSelected(ids, currentPageUnselected);
          this.onSelectChange(currentPageSelected);
        }
      })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({
        dataList: [],
        loading: false
      })
    });
  };
  //表单分页、排序处理
  handleTableChange = (pagination) => {
    let page = pagination.current;
    this.setState({
      page: page - 1,
      pagination,
    }, () => {
      this.getList();
    })
  }
  //处理列表动态更新.若存在则修改，若不存在则添加
  handleListUpdate = (invoiceTypeInfo) => {
    let {dataList, pagination} = this.state;
    let ifExist = false;
    dataList.map(item => {
      if (item.id === invoiceTypeInfo.id) {
        ifExist = true;
        item = invoiceTypeInfo;
      }
    })
    if (!ifExist) {
      pagination.total += 1;
      dataList.unshift(invoiceTypeInfo);
    }
    this.setState({dataList, pagination})
  }
  //规则分配公司取消
  handleAddTaxCodeCancel = () => {
    this.setState({showTaxCodeModal: false})
  }
  //增加税务编码
  handleAddTaxCodeOK = () => {
    let selectValue = this.child.state.selectValue;
    let {invoiceTypeInfo} = this.state;
    if (!selectValue || selectValue.length === 0) {
      this.setState({showTaxCodeModal: false})
      return;
    }
    this.setState({loading: true})
    taxCodeServer.allotTaxNumberToExpenseType(invoiceTypeInfo.id, selectValue, true).then(res => {
      message.success(messages('common.operate.success')/*操作成功*/);
      this.child.restSelectValue();
      this.setState({showTaxCodeModal: false, loading: false})
      this.getList();
    }).catch(e => {
      this.setState({showTaxCodeModal: false, loading: false})
      errorMessage(e.response)
    })
  }
  //取消费用类型MODAL
  handleInvoiceTypeCancel = () => {
    this.setState({showTaxCodeModal: false})
  }
  //点击增加事务编码
  clickAddTaxCode = () => {
    this.setState({showTaxCodeModal: true})
  }
  //选中的行存储
  onSelectChange = (selectedRowKeys) => {
    let {dataAll, reverseSelectionMap, dataList, page} = this.state;
    this.setState({selectedRowKeys: selectedRowKeys});
    if (dataAll) {
      //如果有全选标志，需要记住没选的
      let allKeys = dataList.map(item => {
        return item.id;
      })
      let unSelectedData = CCService.getUnSelected(deepCopy(allKeys), deepCopy(selectedRowKeys));
      reverseSelectionMap[page] = unSelectedData;
      this.setState({
        reverseSelectionMap,
      }, () => {
      })
    } else {
      //不需要记住
      this.setState({
        reverseSelectionMap: {}
      })
    }
  }
  cancelAll = (selectedRowKeys) => {
    this.setState({
      dataAll: false,
      selectedRowKeys: []
    })
  }
  dataAll = (selectedRowKeys) => {
    this.setState({
      dataAll: true,
      reverseSelectionMap: {},//点击一次全选全部就返回
      selectedRowKeys: [...selectedRowKeys]
    }, () => {
    })
  };
  pageAll = (selectedRowKeys) => {
    this.onSelectChange(selectedRowKeys);
    this.setState({
      selectedRowKeys: [...selectedRowKeys],dataAll: false,
    })
  };
  //点击返回
  clickBack = () => {
    let {ruleId} = this.props.params;
    this.context.router.push({
      pathname: menuRoute.getRouteItem('invoice-type').url.replace(':ruleId', ruleId)
    })
  }
  //子组件this
  onRef = (ref) => {
    this.child = ref;
  }

  render() {
    const {columns, pagination, loading, dataList, showTaxCodeModal, invoiceTypeInfo, selectedRowKeys, dataAll, reverseSelectionMap} = this.state;
    const {tenantMode} = this.props;
    let rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      hideDefaultSelections: true,//去掉默认的
      onChange: this.onSelectChange,
      onSelection: this.onSelection,
      selections: [
        {
          key: 'ALL_PAGE',
          text: messages('finance-setting.key130'/*全选全部*/),//全选全部
          onSelect: this.dataAll
        },
        {
          key: 'CURRENT_PAGE',
          text: messages('finance-setting.key131'/*全选当页*/),//'全选当页',
          onSelect: this.pageAll
        },
        {
          key: 'cancel-all',
          text: messages("common.cancel"),//取消
          onSelect: this.cancelAll
        },
      ]
    }
    return (
      <div>
        <div style={{marginBottom: 50}}>
          <Row gutter={16}>
            <Col span={24}>
              <Card title={messages('common.baseInfo')/*基本信息*/}>
                <Col span={6} style={{paddingRight:5}}>
                  <span>{messages('finance-setting.key132'/*费用类别*/)}</span>
                  <br/>
                  {invoiceTypeInfo.expTypeName}
                </Col>
                <Col span={6} style={{paddingRight:5}}>
                  <span>{messages('finance-setting.key72'/*规则名称*/)}</span>
                  <br/>
                  {invoiceTypeInfo.ruleName}
                </Col>
                <Col span={6} style={{paddingRight:5}}>
                  <span>{messages('finance-setting.key133'/*账套名称*/)}</span>
                  <br/>
                  {invoiceTypeInfo.setOfBooksName}
                </Col>
                <Col span={6} style={{paddingRight:5}}>
                  <span>{messages('common.column.status')/*状态*/}</span>
                  <br/>
                  <Badge status={invoiceTypeInfo.enable ? 'success' : 'error'}
                         text={invoiceTypeInfo.enable ? messages("common.status.enable") : messages("common.status.disable")}/>
                </Col>
              </Card>
            </Col>
          </Row>
        </div>
        <div style={{marginBottom: 20}}>
          {tenantMode &&
          <span><Button type="primary" style={{marginRight: 60}} onClick={this.clickAddTaxCode}>{messages('finance-setting.key134'/*批量添加编码*/)}</Button>
            <Button size="small" loading={loading} disabled={selectedRowKeys.length > 0 ? false : !dataAll}
                    onClick={() => this.clickEnable(true)}>{messages('common.status.enable')/*启用*/}</Button> &nbsp;&nbsp;
            <Button size="small" loading={loading} disabled={selectedRowKeys.length > 0 ? false : !dataAll}
                    onClick={() => this.clickEnable(false)}>{messages('common.status.disable')/*禁用*/}</Button></span>}
          <Search
            placeholder={messages('finance-setting.key135'/*输入简称、名称或说明*/)}
            enterButton={true}
            onSearch={(value) => this.searchList(value)}
            style={{width: 200, float: "right"}}
          />
        </div>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total})}</div>
          {/* 共total条数据 */}
        </div>
        <ResizeTable
          rowKey="id"
          rowSelection={tenantMode ? rowSelection : undefined}
          columns={columns}
          dataSource={dataList}
          onChange={this.handleTableChange}
          pagination={pagination}
          loading={loading}
          size="middle"
          bordered
        />
        <a style={{fontSize: '14px', paddingBottom: '20px'}} onClick={this.clickBack}>
          <Icon type="rollback" style={{marginRight: '5px'}}/>{messages('common.back')}
        </a>
        {/*分配税务编码Modal*/}
        <Modal
          title={messages('finance-setting.key136'/*选择分类事务编码*/)}
          visible={showTaxCodeModal}
          onOk={this.handleAddTaxCodeOK}
          onCancel={this.handleAddTaxCodeCancel}
          width={600}
          footer={[
            <Button key="back" onClick={this.handleAddTaxCodeCancel}>{messages('common.back')/*返回*/}</Button>,
            <Button key="submit" type="primary" loading={loading}  onClick={this.handleAddTaxCodeOK}> {messages('finance-setting.key137'/*确认*/)}
            </Button>,
          ]}
          className="list-selector">
          <TaxCodeTreeSelector  showTaxCodeModal={showTaxCodeModal}  onRef={this.onRef}>
          </TaxCodeTreeSelector>
        </Modal>
      </div>
    )

  }

}

TaxCodeClassify.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(TaxCodeClassify);
